package com.lh.pospi.x_store.ui;

import android.content.Intent;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.lh.pospi.x_store.R;
import com.lh.pospi.x_store.adapter.FeatureAdapter;
import com.lh.pospi.x_store.adapter.GirdAdapter;
import com.lh.pospi.x_store.adapter.GoodsItemAdapter;
import com.lh.pospi.x_store.adapter.IndexBrandAdapter;
import com.lh.pospi.x_store.adapter.IndexCatAdapter;
import com.lh.pospi.x_store.adapter.ListAddrAdapter;
import com.lh.pospi.x_store.adapter.ListDataAdapter;
import com.lh.pospi.x_store.adapter.ListDistanseAdapter;
import com.lh.pospi.x_store.app.MyApp;
import com.lh.pospi.x_store.base.BaseActivity;
import com.lh.pospi.x_store.greendao.GoodsBeanDao;
import com.lh.pospi.x_store.modle.BrandBean;
import com.lh.pospi.x_store.modle.CatBean;
import com.lh.pospi.x_store.modle.GoodsBean;
import com.lh.pospi.x_store.ui.inventory.InventoryDetailActivity;
import com.lh.pospi.x_store.ui.overflow.OverflowDetailActivity;
import com.lh.pospi.x_store.ui.purchase.PurchaseDetailActivity;
import com.lh.pospi.x_store.ui.wholesale.WholesaleDetailActivity;
import com.lh.pospi.x_store.view.DialogGoods;
import com.lh.pospi.x_store.view.IndexStickyViewDecoration;
import com.lh.pospi.x_store.view.PopupFilterMenu;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.vondear.rxtool.RxDataTool;
import com.vondear.rxtool.RxKeyboardTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogEditSureCancel;
import com.wind.keyboard.OfoKeyboard;
import com.wind.keyboard.OfoKeyboardView;

import org.greenrobot.greendao.query.QueryBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import cn.ittiger.indexlist.IndexStickyView;
import cn.ittiger.indexlist.listener.OnItemClickListener;

public class GoodsSearchActivity extends BaseActivity implements View.OnClickListener, BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.popup_menu)
    PopupFilterMenu popupFilterMenu;

    private String catCode = "";
    private String brandCode = "";

    private String headers[] = {"品牌", "分类", };
    private List<View> popupViews = new ArrayList<>();
    public static final String MARK = "mark";
    public static final int MARK_PURCHSE_ORDER = 1;//采购订单
    public static final int MARK_WHOLESALE = 2;//批发
    public static final int MARK_OVERFLOW = 3;//报损
    public static final int MARK_INVENTORY = 4;//库存
    public static final int MARK_CHECK = 5;//盘点

    private GoodsItemAdapter itemAdapter;
    private List<GoodsBean> goodsBeans;
    private EditText et_name;
    private List<GoodsBean> selectBeanList;
    private TextView tv_totalNum;
    private int mark;

    @Override
    protected int getContentView() {
        return R.layout.activity_search_goods;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        selectBeanList = new ArrayList<>();//初始化购物车
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_top_search, null);
        et_name = view.findViewById(R.id.et_name);
        et_name.setNextFocusForwardId(R.id.et_name);
        et_name.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                searchData();
                return true;
            }
        });
        view.findViewById(R.id.et_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_name.setText("");
            }
        });
        getTopBar().setCenterView(view);
        getTopBar().setBackgroundColor(getResources().getColor(R.color.whitesmoke));
        QMUIAlphaImageButton button = getTopBar().addLeftBackImageButton();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mContext.finish();
            }
        });
        button.setImageResource(R.mipmap.icon_back);
        Button imageButton = getTopBar().addRightTextButton("搜索", 3);
        imageButton.setOnClickListener(this);
        imageButton.setTextColor(getResources().getColor(R.color._30));
        initData();
        initDrop();
//        et_name.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                OfoKeyboard keyboard = new OfoKeyboard(mContext);
//                keyboard.attachTo(et_name,false);
//            }
//        });


    }

    private void initData() {
        mark = getIntent().getIntExtra(MARK,0);
    }
    private void goBack(){
        Intent intent = new Intent();
        switch (mark) {
            case MARK_PURCHSE_ORDER:
                intent.setClass(this, PurchaseDetailActivity.class);
                intent.putExtra(MARK, (Serializable) selectBeanList);
                startActivity(intent);
                break;
            case MARK_WHOLESALE:
                intent.setClass(this, WholesaleDetailActivity.class);
                intent.putExtra(MARK, (Serializable) selectBeanList);
                startActivity(intent);
                break;
            case MARK_OVERFLOW:
                intent.setClass(this, OverflowDetailActivity.class);
                intent.putExtra(MARK, (Serializable) selectBeanList);
                startActivity(intent);
                break;
            case MARK_INVENTORY:
                intent.setClass(this, InventoryDetailActivity.class);
                intent.putExtra(MARK, (Serializable) selectBeanList);
                startActivity(intent);
                break;

        }
    }

    private void initDrop() {
        BrandBean bean = new BrandBean();
        bean.setCode("");
        bean.setName("#全部");
        CatBean catBean = new CatBean();
        catBean.setCode("");
        catBean.setName("#全部");

        final List<BrandBean> beanList = MyApp.getInstance().getDaoSession().getBrandBeanDao().loadAll();
        beanList.add(0,bean);
        List<CatBean> catBeans = MyApp.getInstance().getDaoSession().getCatBeanDao().loadAll();
        catBeans.add(0, catBean);

        View view = LayoutInflater.from(mContext).inflate(R.layout.index_brand, null);
        IndexStickyView indexStickyView = view.findViewById(R.id.indexStickyView);
        IndexBrandAdapter brandAdapter = new IndexBrandAdapter(mContext, beanList);
        indexStickyView.setAdapter(brandAdapter);
        indexStickyView.addItemDecoration(new IndexStickyViewDecoration(this));
        brandAdapter.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(View childView, int position, Object item) {
                BrandBean brandBean = (BrandBean) item;
                brandCode = brandBean.getCode();
                popupFilterMenu.setTabText(brandBean.getName());
                popupFilterMenu.closeMenu();
                upData();
            }
        });

        View catView = LayoutInflater.from(mContext).inflate(R.layout.index_brand, null);
        IndexStickyView catIndex = catView.findViewById(R.id.indexStickyView);
        IndexCatAdapter catAdapter = new IndexCatAdapter(mContext, catBeans);
        catIndex.setAdapter(catAdapter);
        catIndex.addItemDecoration(new IndexStickyViewDecoration(this));
        catAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View childView, int position, Object item) {
                CatBean catBean = (CatBean) item;
                catCode = catBean.getCode();
                popupFilterMenu.setTabText(catBean.getName());
                popupFilterMenu.closeMenu();
                upData();
            }
        });

        //init popupViews
        popupViews.add(view);
        popupViews.add(catView);


        //init context areaView
        goodsBeans = new ArrayList<>();
        goodsBeans.addAll(getEntys(0));

        View contentView = LayoutInflater.from(mContext).inflate(R.layout.layout_contentview, null);
        final RecyclerView recyclerView = contentView.findViewById(R.id.rv_goods_search);
        tv_totalNum = contentView.findViewById(R.id.tv_totalNum);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        itemAdapter = new GoodsItemAdapter(R.layout.item_search_goods, goodsBeans);
        itemAdapter.setOnItemClickListener(this);
        QMUIRoundButton button = contentView.findViewById(R.id.btn_ok);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goBack();
            }
        });
        recyclerView.setAdapter(itemAdapter);
        itemAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadMore();
                    }
                },1000);

            }
        });
        itemAdapter.disableLoadMoreIfNotFullPage(recyclerView);

        //init PopupMenu
        popupFilterMenu.initPopupMenu(Arrays.asList(headers), popupViews, contentView);

    }
    public List<GoodsBean> getEntys(int offset){
        GoodsBeanDao dao = MyApp.getInstance().getDaoSession().getGoodsBeanDao();
        List<GoodsBean> listMsg = dao.queryBuilder()
                .offset(offset * 20).limit(20).list();
        return listMsg;
    }
    public List<GoodsBean> getEntysByLimit(int offset,String cat,String brand){

        GoodsBeanDao dao = MyApp.getInstance().getDaoSession().getGoodsBeanDao();
        List<GoodsBean> listMsg = new ArrayList<>();
        if (cat.isEmpty() && !brand.isEmpty()) {
           listMsg = dao.queryBuilder().where(GoodsBeanDao.Properties.Brand.eq(brand))
                    .offset(offset * 20).limit(20).list();
        } else if (!cat.isEmpty() && brand.isEmpty()) {
            listMsg = dao.queryBuilder().where(GoodsBeanDao.Properties.Cat.eq(cat))
                    .offset(offset * 20).limit(20).list();
        } else if (cat.isEmpty() && brand.isEmpty()) {
            listMsg = dao.queryBuilder()
                    .offset(offset * 20).limit(20).list();
        } else {
            listMsg = dao.queryBuilder().where(GoodsBeanDao.Properties.Cat.eq(cat),GoodsBeanDao.Properties.Brand.eq(brand))
                    .offset(offset * 20).limit(20).list();
        }

        return listMsg;
    }
    public List<GoodsBean> getEntysByName(int offset,String name){
        GoodsBeanDao dao = MyApp.getInstance().getDaoSession().getGoodsBeanDao();
        QueryBuilder builder = dao.queryBuilder();
        builder.whereOr(GoodsBeanDao.Properties.Code.eq(name),
                GoodsBeanDao.Properties.Name.like("%" + name + "%"),
                GoodsBeanDao.Properties.Barcode.like("%" + name + "%"));
        List<GoodsBean> listMsg = builder.offset(offset * 20).limit(20).list();
        if (listMsg.size() == 0) {
            RxToast.normal("未查询到信息");
        } else {
            RxToast.normal("查询成功");
        }

        return listMsg;
    }

    private void upData(){
        sta = 1;
        goodsBeans.clear();
        goodsBeans.addAll(getEntysByLimit(0, catCode, brandCode));
        itemAdapter.notifyDataSetChanged();
        index = 0;
    }

    private int sta = 0;
    private int index = 0;
    private void loadMore() {
        List<GoodsBean> list = getEntysByLimit(++index, catCode, brandCode);
        if (sta == 2) {
            list = getEntysByName(++index, et_name.getText().toString().trim());
        }
        if (list.size() > 0) {
            itemAdapter.addData(list);
            itemAdapter.loadMoreComplete();
        } else {
            itemAdapter.loadMoreEnd();
        }
    }
    private void searchData(){
        sta = 2;
        goodsBeans.clear();
        goodsBeans.addAll(getEntysByName(0, et_name.getText().toString().trim()));
        itemAdapter.notifyDataSetChanged();
        index = 0;
        itemAdapter.setEnableLoadMore(true);

    }

    @Override
    public void onClick(View view) {
        RxKeyboardTool.hideSoftInput(mContext);
        searchData();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {
        new DialogGoods(mContext).show(goodsBeans.get(position), new DialogGoods.Listener() {
            @Override
            public void getNum(int num) {
                goodsBeans.get(position).setNum(num);
                goodsBeans.get(position).setSelect(true);
                add(goodsBeans.get(position));
                itemAdapter.notifyDataSetChanged();
            }
        });
//        //提示弹窗
//        final RxDialogEditSureCancel rxDialogEditSureCancel = new RxDialogEditSureCancel(this);
//        rxDialogEditSureCancel.setTitle(goodsBeans.get(position).getName());
//        rxDialogEditSureCancel.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
//        rxDialogEditSureCancel.getEditText().setText("1");
//        rxDialogEditSureCancel.getEditText().setSelectAllOnFocus(true);
//
//
//        rxDialogEditSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                closeKey(rxDialogEditSureCancel.getEditText());
//                String s = rxDialogEditSureCancel.getEditText().getText().toString().trim();
//                if (RxDataTool.isInteger(s)) {
//
//                }
//
//
//                rxDialogEditSureCancel.cancel();
//
//            }
//        });
//        rxDialogEditSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                closeKey(rxDialogEditSureCancel.getEditText());
//                rxDialogEditSureCancel.cancel();
//
//
//            }
//        });
//        rxDialogEditSureCancel.show();
//        RxKeyboardTool.toggleSoftInput(mContext,rxDialogEditSureCancel.getEditText());
    }

    private void closeKey(EditText editText){
        RxKeyboardTool.hideSoftInput(mContext, editText);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApp.getInstance().getDaoSession().getGoodsBeanDao().detachAll();
        selectBeanList = null;
    }

    private void add(GoodsBean bean) {

        if (bean != null) {
            selectBeanList.add(bean);
            update();
        }

    }
    private void delete(){

    }
    private void update(){
        int num = 0;
        for (GoodsBean bean : selectBeanList) {
            num += bean.getNum();
        }
        tv_totalNum.setText("合计件数:"+num);

    }

}
